<?php
session_start();
include "mysqli_connection.php";

if (!isset($_SESSION["username"])){
	echo "<script>window.location.href='login.php'</script>";
}
else{
	$filter = "true";
	if (isset($_POST["name"]) && $_POST["name"] !== ""){
		$param = "(name = '" . $mysqli->real_escape_string(trim($_POST["name"])) . "')";
		$filter .= " AND " . $param;
	}
	$perNumber = 25;
	$page = $_POST['page'];
	$count = $mysqli->query("select count(*) from Requirements WHERE " . $filter . ";");
	$rs = mysqli_fetch_array($count);
	$totalNumber = $rs[0];
	if ($totalNumber == 0){
		echo "<div><font color='red'>No result!</font></div>";
	}
	else{
		echo "<div>Found " . $totalNumber. " requirements.</div>";
?>
<div>
<table>
<thead>
<td>ID</td><td>Name</td><td>Groups</td><td>Operation</td>
</thead>
<tbody>
<?php
	}
	$totalPage = ceil($totalNumber / $perNumber);
	if ($page < 1) {
		$page = 1;
	}
	else if ($page > $totalPage){
		$page = $totalPage;
	}
	$startCount = ($page - 1) * $perNumber;
	$result = $mysqli->query("select * from Requirements WHERE (" . $filter .") LIMIT $startCount, $perNumber");
	if ($result){
		$requirement_list = $_POST["requirement_list"];
		while ($row = mysqli_fetch_array($result)){
	?>
<tr>
<td><?php echo $row["r_id"];?></td>
<td><?php echo $row["name"];?></td>
<td><a href="#" id = "toggle_group_link_<?php echo $row["r_id"];?>" onclick = "toggle_group_list(<?php echo $row["r_id"];?>);false;">Show</a><div id = "toggle_group_text_<?php echo $row["r_id"];?>"></div></td>
<td>
<?php
			if ($requirement_list && in_array($row["r_id"], $requirement_list)){
				echo "<a href='javascript:' onclick = 'remove_requirement(" . $row['r_id'] . ");false;'>Remove</a>";
			}
			else{
				echo "<a href='javascript:' onclick = 'add_requirement(" . $row['r_id'] . ",\"" . $row["name"] . "\");false;'>Add</a>";
			}
?>
</td>
</tr>
<?php
		}
	}
}
?>
</tbody>
</table>
</div>
<div>
<?php
echo "<script>currentPage = " . $page . ";</script>";
if ($totalPage > 1){
	if ($page != 1) {
		echo "<a href='javascript:' onclick = 'search_requirement(" . ($page - 1) . ");false;'>Back</a>&nbsp";
	}
	for ( $i = 1; $i <= $totalPage; $i++){
		if ($i == $page){
			echo "&nbsp" . $i . "&nbsp";
		}
		else{
			echo "&nbsp<a href='javascript:' onclick = 'search_requirement(" . $i . ");false;'>" . $i . "</a>&nbsp";
		}
	}
	if ($page < $totalPage) {
		echo "&nbsp<a href='javascript:' onclick = 'search_requirement(" . ($page + 1) . ");false;'>Next</a>";
	}
}
?>
</div>